package cn.jiedh.app.meiweidk.browse;

import android.Manifest;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.florent37.viewanimator.ViewAnimator;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.UI.AlertDialog;
import cn.jiedh.app.meiweidk.Utils.UI.EmptyRecyclerView;
import cn.jiedh.app.meiweidk.Utils.UI.StateLayout;
import cn.jiedh.app.meiweidk.Utils.tool.ActivityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.MobileUtils;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.base.BaseActivity;
import cn.jiedh.app.meiweidk.baseadapter.BaseAdapter;
import cn.jiedh.app.meiweidk.baseadapter.BaseViewHolder;
import cn.jiedh.app.meiweidk.buried.BuriedBean;
import cn.jiedh.app.meiweidk.login.LoginActivity;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;
import cn.jiedh.app.meiweidk.response.BaseResponse;
import cn.jiedh.app.meiweidk.runtimepermissions.PermissionsManager;
import cn.jiedh.app.meiweidk.runtimepermissions.PermissionsResultAction;

/**
 * @name： 常见问题
 * @author： 周毅
 * @phone： 15826080712
 * @createTime： 2017/10/20
 * @modifyTime： 2017/10/20
 * @explain：
 */

public class QuessionActivity extends BaseActivity {
    @BindView(R.id.bar_img_back)
    ImageView barImgBack;
    @BindView(R.id.bar_tv_title)
    TextView barTvTitle;
    @BindView(R.id.bar_tv_other)
    TextView barTvOther;
    @BindView(R.id.view_line)
    View viewLine;
    @BindView(R.id.listview)
    EmptyRecyclerView listview;
    @BindView(R.id.smartrefreshLayout)
    SmartRefreshLayout smartrefreshLayout;
    BaseAdapter<QuessionBean> adapter;
    List<QuessionBean> list = new ArrayList<>();
    int currentExpendPosition = -1;
    @BindView(R.id.statelayout)
    StateLayout stateLayout;
//    @BindView(R.id.tv_phone)
//    TextView tvPhone;
    @BindView(R.id.empty_nn_pic)
    ImageView emptyNnPic;
    @BindView(R.id.empty_nn_btn)
    TextView emptyNnBtn;
    private View emptyview;

    private List<BuriedBean> buriedList;

    @Override
    protected int getLayoutView() {
        return R.layout.act_quession;
    }


    @Override
    protected void initView(View view) {
        barTvTitle.setText("帮助中心");
        stateLayout.setOnNoClick(view12 -> smartrefreshLayout.autoRefresh());
        adapter = new BaseAdapter<QuessionBean>(this, R.layout.quession_item, list) {
            @Override
            public void convert(BaseViewHolder holder, QuessionBean quessionBean, int position) {
                RelativeLayout rl_title = holder.getView(R.id.rl_title);
                TextView contentTV = holder.getView(R.id.content_tv);
                holder.setText(R.id.content_tv, quessionBean.getAnswer());
                holder.setText(R.id.title_civ, quessionBean.getProblem());
                final ImageView img = holder.getView(R.id.img);
                if (position != currentExpendPosition) {//其他显示的都隐藏
                    contentTV.setVisibility(View.GONE);
//                    list.get(position).setShown(false);
                    ViewAnimator.animate(contentTV)
                            .pivotX(0.5f)
                            .pivotY(0f)
                            .scaleY(0, 1)
                            .andAnimate(img)
                            .rotation(0)
                            .accelerate()
                            .duration(100)
                            .start();

                } else if (position == currentExpendPosition) {
                    if (quessionBean.isShown()) {//隐藏
                        contentTV.setVisibility(View.VISIBLE);
//                        list.get(position).setShown(false);
                        ViewAnimator.animate(contentTV)
                                .pivotX(0.5f)
                                .pivotY(0f)
                                .scaleY(0, 1)
                                .andAnimate(img)
                                .rotation(180)
                                .accelerate()
                                .duration(100)
                                .start();

                    } else {//显示
                        contentTV.setVisibility(View.GONE);
//                        list.get(position).setShown(true);
                        ViewAnimator.animate(contentTV)
                                .pivotX(0.5f)
                                .pivotY(0f)
                                .scaleY(1, 0)
                                .andAnimate(img)
                                .rotation(0)
                                .decelerate()
                                .duration(100)
                                .start();
                    }
                }

                rl_title.setOnClickListener(view1 -> {
                    MobclickAgent.onEvent(activity,"my_help_question_click");
                    SPUtils.saveBuried("click","7","帮助中心-每个问题点击-" + quessionBean.getProblem(),
                            "","我的-帮助中心","","","");
                    currentExpendPosition = position;
                    for(QuessionBean bean:list){
                        if(list.indexOf(bean)!=position){
                            bean.setShown(false);
                        }
                    }
                    list.get(position).setShown(list.get(position).isShown()?false:true);
                    adapter.notifyDataSetChanged();
                });
            }
        };
        listview.setLayoutManager(new LinearLayoutManager(this));
        listview.setAdapter(adapter);
        smartrefreshLayout.autoRefresh();
        smartrefreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）
        smartrefreshLayout.setOnRefreshListener(refreshLayout -> refreshLayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                stateLayout.netviewGone();
                getQuesstionList();
                refreshLayout.finishRefresh();
            }
        }, 2000));
    }

    @Override
    protected void initData() {
        emptyview = findViewById(R.id.emptyview);
        emptyNnBtn.setText("暂无常见问题~");
        emptyNnPic.setImageResource(R.mipmap.zwcjwt);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    @OnClick({R.id.bar_img_back,R.id.opinion_feedback})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bar_img_back:
                finish();
                break;
//            case R.id.tv_phone:
//                getRoot();
//                break;
            case R.id.opinion_feedback:
                if (!SPUtils.getIsLogin()) {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("isGoHome",true);
                    ActivityUtil.next(this, LoginActivity.class,bundle);
                } else {
                    MobclickAgent.onEvent(activity,"my_help_feedback_click");
                    ActivityUtil.next(this, OpinionFeedbackActivity.class);
                    SPUtils.saveBuried("click","7","帮助中心-用户反馈点击","",
                            "我的-帮助中心","","","");
                }
                break;
            default:
                break;
        }
    }

    public void getRoot() {
        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(this, new String[]{
                Manifest.permission.CALL_PHONE}, new PermissionsResultAction() {
            @Override
            public void onGranted() {
                callPhone();
            }

            @Override
            public void onDenied(String permission) {
                showDialog();
            }
        });
    }

    private void callPhone() {
        new AlertDialog(this).builder().setTitle("拨打").setMsg(SPUtils.getAppInfoFromSP().getCustomerServicePhone()).setNegativeButton("取消", view -> {

        }).setPositiveButton("确定", view2 -> ActivityUtil.Phone(QuessionActivity.this, SPUtils.getAppInfoFromSP().getCustomerServicePhone())).show();
    }

    private void showDialog() {
        new AlertDialog(this).builder().setTitle("未开启拨打权限").setMsg("跳转至设置界面").setNegativeButton("取消", view2 -> {

        }).setPositiveButton("确定", view -> MobileUtils.getAppDetailSettingIntent(QuessionActivity.this)).show();
    }


    public void getQuesstionList() {
        request(this, UrlUtils.QUESTIONLIST, new HashMap<>(), false, new ResponseSuccess<QuesstionData>() {
            @Override
            public void onRequestSucceed(BaseResponse<QuesstionData> response) {
                if (response.getCode() == 0) {
                    List<QuessionBean> mlist = response.getData().getDataList();
                    list.clear();
                    list.addAll(mlist);
                    listview.setEmptyView(emptyview);
                    adapter.notifyDataSetChanged();
                }
            }
        }, (error, msg) -> {
            stateLayout.netviewGone();
            list.clear();
            listview.setEmptyView(findViewById(R.id.emptyview));
            adapter.notifyDataSetChanged();
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
    }
}
